<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="dialogFormVisible = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ cancelId(row.formOfEmployment) }}
            </template>

          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template #default="{row}">
              {{ formaDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="dolete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 3, 5, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          > />
          </el-pagination></el-row>
      </el-card>
      <!--弹层  -->
      <el-dialog title="新增员工" :visible.sync="dialogFormVisible" @close="hCloseDialog">
        <empDialog ref="add" @success="hClose" @close="ddd" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import PageTools from '@/components/PageTools'
import { allajax, delEmployee } from '@/api/employees'
import employees from '@/constant/employees'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs'
const hireType = employees.hireType.reduce((sum, item) => {
  sum[item.id] = item.value
  return sum
}, {})
export default {
  components: {
    PageTools,
    empDialog
  },
  data() {
    return {
      page: 1,
      size: 5,
      total: 0,
      list: [],
      hireType: employees.hireType,
      dialogFormVisible: false
    }
  },
  created() {
    this.loadall()
  },
  methods: {
    // 聘用形式函数瞎搞
    cancelId(val) {
      const hireType = {}
      employees.hireType.forEach(item => {
        hireType[item.id] = item.value
      })
      return hireType[val] ? hireType[val] : '未知'
    },
    // 分页函数
    handleSizeChange(val) {
      this.size = val
      this.loadall()
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadall()
    },
    // 全部角色
    async loadall() {
      try {
        const res = await allajax(this.page, this.size)
        this.list = res.data.rows
        this.total = res.data.total
        console.log(res, '全部员工')
      } catch (error) {
        console.log(error)
      }
    },
    // 删除角色
    async deleteEmployee(id) {
      try {
        await delEmployee(id)
      } catch (error) {
        console.log(error)
      }
    },
    // 确认删除
    dolete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteEmployee(id)
        this.loadall()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 子传父
    hClose() {
      this.total++
      const parent = Math.ceil(this.total / this.size)
      this.page = parent
      this.dialogFormVisible = false
      this.loadall()
    },
    hCloseDialog() {
      this.$refs.add.reser()
    },
    ddd() {
      this.dialogFormVisible = false
    },
    // 格式化时间
    formaDate(timer) {
      return dayjs(timer).format('YYYY-MM-DD')
    },
    // 导出
    formData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 取出一个数据对象
      const one = list[0]
      // 判断one是否有值，如果没有直接终止程序
      if (!one) {
        //   list中没有数据
        return
      }
      console.log(Object.keys(one))
      // 使用对象生成需要的header数据
      const header = Object.keys(one).map(enKey => {
        return map[enKey]
      })
      console.log(header)

      const data = list.map(item => {
        //    item['formOfEmployment'] ====> 1 或者 2
        // hireType===> {1:'正式',2:'非正式'}
        item['formOfEmployment'] = hireType[ item['formOfEmployment']] || '未知'
        item['correctionTime'] = item['correctionTime'] || '-'

        return Object.values(item)
      })

      return { header, data }
    },
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await allajax(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }

  }

}
</script>
